<?php

namespace backend\controllers;

use common\models\CouponCategory;
use Yii;
use common\models\Activity;
use common\models\Product;
use backend\models\ActivitySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * ActivityController implements the CRUD actions for Activity model.
 */
class ActivityController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete,shelf' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Activity models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ActivitySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Activity model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Activity model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Activity();
        Yii::$app->session->set('checkgoods','');

        if(Yii::$app->request->isPost){
            $goods='';
            $goods_info = Yii::$app->request->post("goods_info");
            $goodsstr=explode("@@@",$goods_info);
            // --------------快速去重（两次反转加恢复序列）
            $goodsstr = array_flip($goodsstr);
            $goodsstr = array_flip($goodsstr);
            $goodsstr = array_merge($goodsstr);
            //---------------
            foreach($goodsstr as $goodstr){
                $res=[];
                if(!empty($goodstr)){
                    parse_str($goodstr,$res);
//                    var_dump($res);
                    $model1 = new Product();
                    if ($model1->load($res) && $model1->save()) {
//                        var_dump($model1->id);
//                        exit;
                        $goods.=','.$model1->id;
                    }else{
                        var_dump($model1->getErrors());
                        exit;
                    }
                }

            }

            if(substr($goods,0,1)==","){
                $goods=substr($goods,1);
            }


            $model->pic = UploadedFile::getInstance($model,'pic');
            if($model->pic){
                $data=$model->upload();
                if($data){

                    $model->banner=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
            $model->pic1 = UploadedFile::getInstance($model,'pic1');
            if($model->pic1){
                $data=$model->upload1();
                if($data){

                    $model->other_entry=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
            $model->pic2 = UploadedFile::getInstance($model,'pic2');
            if($model->pic2){
                $data=$model->upload2();
                if($data){

                    $model->share_img=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
        }
        if ($model->load(Yii::$app->request->post())   && $model->save()) {
            Activity::updateAll(['goods'=>$goods],['id'=>$model->id]);
            Product::updateAll(["activity_id"=>$model->id],["id"=>$goods]);
            $products = Product::findAll(['id'=>$goods]);
            foreach($products as $product){
                $coupon_id=$product->coupon_id;
                CouponCategory::updateAll(['local_mark_id'=>'tuangou_'.$model->id],['id'=>$coupon_id]);
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Activity model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isPost){
            $goods='';
            $goods_info = Yii::$app->request->post("goods_info");
//            var_dump($goods_info);exit;
            $goodsstr=explode("@@@",$goods_info);
            // --------------快速去重（两次反转加恢复序列）
            $goodsstr = array_flip($goodsstr);
            $goodsstr = array_flip($goodsstr);
            $goodsstr = array_merge($goodsstr);
            //---------------
//              var_dump($goodsstr);exit;
            foreach($goodsstr as $goodstr){
                $res=[];
                if(!empty($goodstr)){
                    parse_str($goodstr,$res);
//                  var_dump($res);exit;
                    if(empty($res['Product']['id'])){
                        $model1=new Product();
                    }else{
                        $model1 = Product::findOne($res['Product']['id']);
                    }
                    if ($model1->load($res) && $model1->save()) {
                        $goods.=','.$model1->id;
                    }else{
                        var_dump($model1->getErrors());
                        exit;
                    }

                }

            }

            if(substr($goods,0,1)==","){
                $goods=substr($goods,1);
            }
            $old_goods_arr = explode(",",$model->goods);
            $new_goods_arr = explode(",",$goods);
            foreach($old_goods_arr as $old_good){
                if(!in_array($old_good,$new_goods_arr)){
                    Product::deleteAll(['id'=>$old_good]);
                }
            }
            foreach($new_goods_arr as $new_good){
                if(!in_array($new_good,$old_goods_arr)){
                    Product::updateAll(['activity_id'=>$id],['id'=>$new_good]);
                }
            }

            $model->pic = UploadedFile::getInstance($model,'pic');

            if($model->pic){
                $data=$model->upload();
                if($data){

                    $model->banner=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
            $model->pic1 = UploadedFile::getInstance($model,'pic1');
            if($model->pic1){
                $data=$model->upload1();
                if($data){

                    $model->other_entry=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
            $model->pic2 = UploadedFile::getInstance($model,'pic2');
            if($model->pic2){
                $data=$model->upload2();
                if($data){

                    $model->share_img=$data;
                }else{
                    return json_encode($model->errors);
                }
            }
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            Activity::updateAll(['goods'=>$goods],['id'=>$id]);
            $products = Product::findAll(['id'=>$goods]);
            foreach($products as $product){
                $coupon_id=$product->coupon_id;
                CouponCategory::updateAll(['local_mark_id'=>'tuangou_'.$model->id],['id'=>$coupon_id]);
            }

            return $this->redirect(['view', 'id' => $id]);
        }
//        if(!empty($model->goods)){
//            Yii::$app->session->set('checkgoods',$model->goods);
//        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Activity model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
    public function actionDeleteSelect(){
        $ids=Yii::$app->request->post("selection");
        return Activity::deleteAll(['id'=>$ids]);

    }
    /**
     * Finds the Activity model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Activity the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Activity::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    public function actionShelf(){
        $id=Yii::$app->request->post('id');
        if(is_array($id)){

            $models = Activity::findAll(['id'=>$id]);
            $tmp_status1=[];
            $tmp_status2=[];
            foreach($models as $model){
                if($model->status==1){
                   $tmp_status1[]=$model->id;
                }else{
                    $tmp_status2[]=$model->id;
                }
            }
            Activity::updateAll(['status'=>2],['id'=>$tmp_status1]);
            Activity::updateAll(['status'=>1],['id'=>$tmp_status2]);
            return 1;
        }else{

            $model=Activity::findOne($id);

            $model->status=$model->status==1?2:1;
            if($model->save()){
                return $this->redirect(Yii::$app->request->referrer);
            }else{
//                var_dump($model->getErrors());
                Yii::$app->session->setFlash("error",$model->getErrors());
            }
            return $this->redirect(Yii::$app->request->referrer);
        }


    }
}
